package com.primaryedu.ui.repair;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.primaryedu.R;
import com.primaryedu.adapter.MyRepairAdapter;
import com.primaryedu.bean.RepairBean;
import com.primaryedu.data.Contants;
import com.primaryedu.data.GlobalData;
import com.primaryedu.ui.BaseActivity;
import com.primaryedu.utils.Utils;
import com.primaryedu.widget.MyListView;
import com.primaryedu.widget.PullToRefreshView;
import com.primaryedu.widget.PullToRefreshView.OnFooterRefreshListener;
import com.primaryedu.widget.PullToRefreshView.OnHeaderRefreshListener;

/**
 * 我的报修
 *
 * @author jun.wang
 * @description
 * @data 2016年12月14日
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@SuppressLint("ResourceAsColor")
public class MyRepairActivity extends BaseActivity implements OnClickListener, OnHeaderRefreshListener, OnFooterRefreshListener {
    private String TAG = MyRepairActivity.class.getSimpleName();
    private MyListView listView;
    MyRepairAdapter adapter;
    private TextView text_right;
    private List<RepairBean> list = new ArrayList<>();
    private List<RepairBean> tempList = new ArrayList<>();
    private final static int REQUESTCODEREPAIR = 1; // "申请"返回的结果码
    private final static int REQUESTCODEAPPROVE = 2; // "申请"返回的结果码
    private Handler handler = new Handler() {

        public void handleMessage(android.os.Message msg) {

            switch (msg.what) {
                case 1001:
                    if (null != tempList && tempList.size() != 0) {
                        adapter = new MyRepairAdapter(MyRepairActivity.this, Utils.getRepairList(tempList));
                        listView.setAdapter(adapter);
                    }
                    break;
                case 1002:
                    if (tempList != null && tempList.size() != 0) {
                        adapter.updateView(tempList);
                    }
                    break;

                default:
                    break;
            }
        }

        ;
    };

    private PullToRefreshView pullToRefreshView;
    private int page = 1;
    private boolean fistenter = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        setContentView(R.layout.activity_my_repair);
        init();
    }

    private void init() {
        Intent intent = getIntent();
        String title = intent.getStringExtra("title");
        ((TextView) this.findViewById(R.id.title)).setText(title);
        listView = (MyListView) this.findViewById(R.id.listView);
        findViewById(R.id.right).setVisibility(View.VISIBLE);
        text_right = (TextView) this.findViewById(R.id.text_right);
        text_right.setText("报修");
        text_right.setTextColor(getResources().getColor(R.color.main_button));
        text_right.setBackground(null);
        text_right.setOnClickListener(this);
        findViewById(R.id.back).setOnClickListener(this);
        listView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                Log.i(TAG, "getuserType================: " + GlobalData.getUsertype(getApplicationContext()));

                if (GlobalData.getUsertype(getApplicationContext()).contains("6")) {//6 报修管理员
                    Intent intent = new Intent(MyRepairActivity.this, RepairApproveActivity.class);
                    GlobalData.repairBean = tempList.get(position);
                    startActivityForResult(intent, REQUESTCODEAPPROVE);
                } else {
                    Intent intent = new Intent(MyRepairActivity.this, RepairDetailsActivity.class);
                    GlobalData.repairBean = tempList.get(position);
                    System.out.println("repairBean==" + GlobalData.repairBean);
                    startActivity(intent);
                }
            }
        });

        pullToRefreshView = (PullToRefreshView) this.findViewById(R.id.main_pull_refresh_view);
        pullToRefreshView.setOnHeaderRefreshListener(this);
        pullToRefreshView.setOnFooterRefreshListener(this);
        pullToRefreshView.setLastUpdated(new Date().toLocaleString());

        requestData(fistenter);
    }

    @Override
    protected int BindLayout() {
        return R.layout.activity_my_repair;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.text_right:
                intent = new Intent(MyRepairActivity.this, RepairServiceActivity.class);
                startActivityForResult(intent, REQUESTCODEREPAIR);
                break;
            case R.id.back:
                finish();
                break;
            default:
                break;
        }
    }

    private void requestData(boolean fistenter) {
        if (fistenter) {
            showLoading("加载中...");
        }
        page = 1;
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getRepair,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        dismissLoading();
                        System.out.println("getRepair==" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");
                            if (result == 1) {
                                String data = json.getString("data");
                                JSONObject listObj = new JSONObject(data);
                                String listStr = listObj.getString("list");

                                list = new Gson().fromJson(listStr,
                                        new TypeToken<List<RepairBean>>() {
                                        }.getType());
                                tempList.clear();
                                tempList.addAll(list);
                                handler.sendEmptyMessage(1001);
                                System.out.println("getNotice==" + list);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                errorLoading("加载失败，请下拉刷新！");
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                //在这里设置需要post的参数
                Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                if (GlobalData.getUsertype(getApplicationContext()).contains("6")) {

                } else {
                    map.put("userid", GlobalData.getUserId(getApplicationContext()));
                }
                return map;
            }
        };
        requestQueue.add(stringRequest);
    }

    private void requestRepairmorelist() {
        StringRequest stringRequest = new StringRequest(Request.Method.POST, Contants.getRepair,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        System.out.println("response=leavelist=" + response);
                        page++;
                        try {
                            JSONObject json = new JSONObject(response);
                            int result = json.getInt("result");

                            if (result == 1) {
                                String data = json.getString("data");
                                if (data.contains("list")) {
                                    JSONObject listObj = new JSONObject(data);
                                    String listStr = listObj.getString("list");
                                    System.out.println("response=listStr=" + listStr);
                                    list = new Gson().fromJson(listStr,
                                            new TypeToken<List<RepairBean>>() {
                                            }.getType());

                                    tempList.addAll(list);
                                    handler.sendEmptyMessage(1002);
                                } else {
//									if (listStr == null){
                                    showToast("已经加载完全部数据！");
                                }
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> map = new HashMap<String, String>();
//				 Map<String, String> map = new HashMap<String, String>();
                map.put("pageSize", "10");
                map.put("pageNo", page + "");
                if (GlobalData.getUsertype(getApplicationContext()).contains("6")) {

                } else {
                    map.put("userid", GlobalData.getUserId(getApplicationContext()));
                }
                return map;

            }
        };
        requestQueue.add(stringRequest);
    }

    @Override
    public void onFooterRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {

            @Override
            public void run() {
                requestRepairmorelist();
                pullToRefreshView.onFooterRefreshComplete();
            }

        }, 1500);
    }

    @Override
    public void onHeaderRefresh(PullToRefreshView view) {
        pullToRefreshView.postDelayed(new Runnable() {
            @Override
            public void run() {
                requestData(false);
                pullToRefreshView.onHeaderRefreshComplete("更新于:"
                        + Calendar.getInstance().getTime().toLocaleString());
                pullToRefreshView.onHeaderRefreshComplete();
                Toast.makeText(MyRepairActivity.this, "数据刷新完成!", Toast.LENGTH_LONG).show();
            }

        }, 1500);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        // RESULT_OK，判断另外一个activity已经结束数据输入功能，Standard activity result:
        // operation succeeded. 默认值是-1
        if (resultCode == 3) {
            if (requestCode == REQUESTCODEREPAIR) {
                requestData(true);
            }
            if (requestCode == REQUESTCODEAPPROVE) {
                requestData(true);
            }
        }
    }
}
